#!/bin/bash

# 检查是否传递了参数
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 {build|clean|run}"
    exit 1
fi
# 获取脚本所在的目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 推断 Makefile 所在的目录（假设 Makefile 在脚本目录的上一级）
MAKEFILE_DIR="$(dirname "$SCRIPT_DIR")"

# nohup.out 文件路径
NOHUP_FILE="$SCRIPT_DIR/nohup.out"

# 检查 nohup.out 文件是否存在，如果不存在则创建
if [ ! -f "$NOHUP_FILE" ]; then
    touch "$NOHUP_FILE"
fi

# 根据参数执行相应的 make 命令
case "$1" in
    build)
        echo "===== Starting build at $(date) =====" >> "$NOHUP_FILE"
        make -C "$MAKEFILE_DIR"  build &>> $NOHUP_FILE
        echo "===== Finished build at $(date) =====" >> "$NOHUP_FILE"
        ;;
    clean)
        echo "===== Starting clean at $(date) =====" >> "$NOHUP_FILE"
        make -C "$MAKEFILE_DIR"  clean &>> $NOHUP_FILE
        echo "===== Finished clean at $(date) =====" >> "$NOHUP_FILE"
        ;;
    run)
        echo "===== Starting run at $(date) =====" >> "$NOHUP_FILE"
        make -C "$MAKEFILE_DIR"  run &>> $NOHUP_FILE
        echo "===== Finished run at $(date) =====" >> "$NOHUP_FILE"
        ;;
    *)
        echo "Invalid option: $1"
        echo "Usage: $0 {build|clean|run}"
        exit 1
        ;;
esac
